#include "ourhdr.h"
#include <fcntl.h>
#include <unistd.h>
#define BUFSIZE 1024

int main(int argc, char * argv[]) {
    int fd;
    int n;
    long unsigned cont_len= 0;
    char buf[BUFSIZE];

    if (argc != 2)   
        err_quit("Usage: %s <filename>.\n", argv[0]);

    if ((fd= open(argv[1], O_RDWR | O_APPEND)) < 0)
        err_sys("Open file %s failed", argv[1]);
   
    // output file content
    puts("The file contents: ");
    while ((n = read(fd, buf, BUFSIZE)) > 0) {
        cont_len+= n;
        if (write(STDOUT_FILENO, buf, n) < n)
            err_sys("Write failed");
    }

    if (cont_len < 100)
        err_quit("Sorry, cant continue, file must have at least 100 char.");

    puts("read 10 char from file start at offset 5.");
    if (lseek(fd, 5, SEEK_SET) == -1) 
        err_sys("lseek failed");

    if ((n = read(fd, buf, 10)) < 0)
        err_sys("read failed");
    
    buf[n] = 0;
    puts(buf);

    puts("write 10 char to file start at offset 20");
    puts("write content: AABBCCDDEE");

    if (lseek(fd, 20, SEEK_SET) == -1) 
        err_sys("lseek failed");
   
    write(fd, "AABBCCDDEE", 10);
}
